var fs = require("fs");
var path = require("path")
var PropertiesReader = require('properties-reader');
var execFileSync = require('child_process').execFileSync;

var properties = PropertiesReader('config.properties');
var phpPath = properties.get('path.php');
var phpDcPath = properties.get('path.php.dc');

var arguments = process.argv.splice(2);
var dir = arguments[0];

readDirSync(dir);
function readDirSync(dirpath){  
    var pa = fs.readdirSync(dirpath);  
    pa.forEach(function(ele,index){  
        var fullpath = path.join(dirpath,ele);
        var info = fs.statSync(fullpath);  
        if(info.isDirectory()){  
            readDirSync(fullpath);  
        }else{  
            var postfix = ".php"
            var i = ele.lastIndexOf(postfix);
            if(-1 != i && i + postfix.length == ele.length){
                // console.log("file: "+ele);
                if(isZended(fullpath)){
                    var destpath = fullpath.replace(dir,path.join(__dirname,"decode"));
                    dezender(fullpath,destpath);
                }
            }
        }     
    })  
}

function isZended(filepath){
    var buffer = fs.readFileSync(filepath);
    if(-1 != buffer.toString().indexOf("@Zend;")){
        return true;
    }else{
        return false;
    }
}

function dezender(filepath,destpath){
    var cmdStr = phpPath + " " + phpDcPath + " " + filepath; 
    mkdirsSync(path.dirname(destpath));
    var out = execFileSync(phpPath,[phpDcPath,filepath]);
    fs.writeFileSync(destpath,out);
}

function mkdirs(dirpath, mode, callback) {
    fs.exists(dirpath, function(exists) {
        if(exists) {
                callback(dirpath);
        } else {
                //尝试创建父目录，然后再创建当前目录
                mkdirs(path.dirname(dirpath), mode, function(){
                        fs.mkdir(dirpath, mode, callback);
                });
        }
    });
};

function mkdirsSync(dirpath) {
    if(!fs.existsSync(dirpath)){
        var dirname = path.dirname(dirpath);
        mkdirsSync(dirname);
        fs.mkdirSync(dirpath);
    }
};